package com.ht.medicaltreatment.view

import android.content.Context
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gym.baselib.base.BaseActivity
import com.gym.baselib.utils.ProgressUtils
import com.hjq.http.EasyHttp
import com.hjq.http.listener.OnHttpListener
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.bean.FromBean
import com.ht.medicaltreatment.bean.FromData
import kotlinx.android.synthetic.main.dialog_sample_from_layout.recyclerView

/**
 * 样本来源
 */
class SampleFromDialog(context: Context):BaseDialog(context), OnItemClickListener {
    override fun getLayoutRes(): Int {
        return R.layout.dialog_sample_from_layout
    }
    private var adapter:ItemAdapter
    private var onClick:(String,Int)->Unit = {name,id -> }
    init {
        recyclerView.layoutManager = LinearLayoutManager(context)
        adapter = ItemAdapter()
        adapter.setOnItemClickListener(this)
        recyclerView.adapter = adapter

        initData()
    }

    private fun initData() {
        ProgressUtils.showProgress()
        EasyHttp.post(ActivityUtils.getTopActivity() as BaseActivity)
            .api("/other/app_sampleSourceDict/findAllSampleSourceDictList.do")
            .request(object : OnHttpListener<FromBean>{
                override fun onHttpSuccess(result: FromBean) {
                    ProgressUtils.dismiss()
                    adapter.setNewInstance(result.data)
                }

                override fun onHttpFail(e: Exception) {
                    ProgressUtils.dismiss()
                    ToastUtils.showShort(e.message)
                }
            })
    }

    fun show(onClick:(String, Int)->Unit) {
        super.show()
        this.onClick = onClick
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = adapter.getItem(position) as FromData
        onClick(item.name,item.id)
        dismiss()
    }

    class ItemAdapter : BaseQuickAdapter<FromData, BaseViewHolder>(R.layout.item_list_layout){
        override fun convert(holder: BaseViewHolder, item: FromData) {
            val line = holder.getView<View>(R.id.line)
            if(getItemPosition(item) == 0){
                line.visibility = View.GONE
            }else{
                line.visibility = View.VISIBLE
            }
            holder.setText(R.id.tvName,item.name)
        }
    }
}
